
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "iostream"
#include "f_func.h"

using namespace std;

int main(int argc, char* argv[])
{
	
	const char* _f_ = "write";
	FILE* ext;
	struct stat fs_stat;
	int	block_num = 0;
	int i,type;
	string file_name;
	char file_num[300];
	char* zeros;
	
	if(argc<3){
#ifdef PRINT_MSG
		printf("[%s]: use %s N filename \n",_f_,_f_); 
#endif
	return 1;
	}
	
	
	if(sscanf(argv[1],"%d",&block_num)==0)
	{
		#ifdef PRINT_MSG
			printf("[%s]: first param error %s\n",_f_,argv[1]); 
		#endif
			return -1;
	}
	
	file_name = argv[2];
	if(!check_disks()){
		#ifdef PRINT_MSG
			printf("[%s]: Use rebuild\n",_f_); 
		#endif
		return -1;
	
	}
	ext = fopen(file_name.data(),"rb+");
	if(ext==NULL)
	{
		close_raid_files();
		#ifdef PRINT_MSG
			printf("[%s]: can't open file %s\n",_f_,argv[2]); 
		#endif
		return -1;
	}
	
	if(stat(file_name.data(),&fs_stat)!=0) 
	{
#ifdef PRINT_MSG
		printf("[%s]: Can't get extern file stats %s\n",_f_,file_name.data());
#endif
		return -1;
	}
	

	if(fs_stat.st_size>data.size_block)
	{
		close_raid_files();
		#ifdef PRINT_MSG
			printf("[%s]: file size %d more then block size %d \n",_f_,(int)fs_stat.st_size,data.size_block); 
		#endif
		return -1;
	}

	if(block_num<0)
	{
		close_raid_files();
		#ifdef PRINT_MSG
			printf("[%s]: number of block must be >0  \n",_f_); 
		#endif
		return -1;
	}
	if(block_num>data.num_blocks ){
		close_raid_files();
		#ifdef PRINT_MSG
			printf("[%s]: number of block must be <= %d  \n",_f_,data.num_blocks); 
		#endif
		return -1;
	}
	if(!(*write_raid_func)(ext,block_num,(int)fs_stat.st_size))
	{
		close_raid_files();
		#ifdef PRINT_MSG
			printf("[%s]: writing in block error  \n",_f_); 
		#endif
		return -1;
	}

	close_raid_files();
	return 0;
	
	
}

